package com.aliyun.heiyu.common.util.sm4cbc;

import com.aliyun.heiyu.common.util.PropertiesUtil;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

public class SM4Util {
    private static byte[] keyBytes = Util.hexStringToBytes(PropertiesUtil.getValue("jdbcConfig.properties", "privateKey"));
    private static byte[] ivBytes = Util.hexStringToBytes("9446A1C65749AE61FB417D5C67BEDA51");

    public static String encrypt_CBC(String data){
        try {
            byte[] bytes = SM4EnDecryption.encrypt_Cbc_Padding(keyBytes, ivBytes, data.getBytes());
            String s = Util.byteToHex(bytes);
            return s;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String decrypt_CBC(String data){
        try {
            byte[] bytes = SM4EnDecryption.decrypt_Cbc_Padding(keyBytes, ivBytes, Util.hexToByte(data));
            String s = Util.byteToString(bytes);
            return s;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return "";
    }


}
